package com.example.rbacmanage.controller;

import com.example.rbacmanage.annotation.LogAnnotation;
import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.common.enums.ConfigEnums;
import com.example.rbacmanage.entity.User;
import com.example.rbacmanage.service.SysCaptchaService;
import com.example.rbacmanage.service.UserService;
import com.example.rbacmanage.util.JwtTokenUtil;
import com.example.rbacmanage.util.ParamResolver;
import com.example.rbacmanage.vo.CaptchaResult;
import com.example.rbacmanage.vo.UserLoginReq;
import com.example.rbacmanage.vo.UserPageQueryReq;
import com.example.rbacmanage.vo.UserRegisterReq;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/system/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private SysCaptchaService sysCaptchaService;

    @GetMapping(value = "/list")
    @PreAuthorize("hasAnyAuthority('system:user:list')")
    public Result list(UserPageQueryReq req) {
        User user = new User();
        user.setPage(req.getPage());
        user.setLimit(req.getLimit());
        user.setUserName(req.getUserName());
        user.setPhone(req.getPhone());
        user.setDeptId(req.getDeptId());
        PageInfo<User> page = userService.getPage(user);
        return Result.success(page);
    }

    @GetMapping(value = "/assignUserPage")
    @PreAuthorize("hasAnyAuthority('system:user:assignUserPage')")
    public Result assignUserPage(UserPageQueryReq req) {
        User user = new User();
        user.setPage(req.getPage());
        user.setLimit(req.getLimit());
        user.setUserName(req.getUserName());
        user.setPhone(req.getPhone());
        user.setRoleId(req.getRoleId());
        PageInfo<User> page = userService.getAssignUserPage(user);
        return Result.success(page);
    }

    /**
     * 查询未授权角色的用户
     * @param req
     * @return
     */
    @PreAuthorize("hasAnyAuthority('system:user:unAssignUserPage')")
    @GetMapping(value = "/unAssignUserPage")
    public Result unAssignUserPage(UserPageQueryReq req) {
        User user = new User();
        user.setPage(req.getPage());
        user.setLimit(req.getLimit());
        user.setUserName(req.getUserName());
        user.setPhone(req.getPhone());
        user.setRoleId(req.getRoleId());
        PageInfo<User> page = userService.getUnAssignUserPage(user);
        return Result.success(page);
    }

    @GetMapping(value = "/getOne")
    public Result getOne(@RequestParam("id") Long id) {
        return Result.success(userService.getById(id));
    }

    @LogAnnotation(module = "用户模块", operation = "删除用户")
    @DeleteMapping(value = "/delete")
    @PreAuthorize("hasAnyAuthority('system:user:delete')")
    public Result delete(@RequestBody Long[] ids) {
        userService.remove(ids);
        return Result.success();
    }

    @LogAnnotation(module = "用户模块", operation = "修改用户")
    @PutMapping(value = "/update")
    @PreAuthorize("hasAnyAuthority('system:user:edit')")
    public Result update(@RequestBody User user) {
        userService.update(user);
        return Result.success();
    }

    @LogAnnotation(module = "用户模块", operation = "新增用户")
    @PostMapping(value = "/add")
    public Result add(@RequestBody User user) {
        userService.save(user);
        return Result.success();
    }

    @GetMapping(value = "/getLoginInfo")
    public Result getLoginInfo() {
        return Result.success(userService.getLoginInfo());
    }

    @PostMapping(value = "/login")
    public Result login(@RequestBody UserLoginReq req) {
        // 获取系统验证码开关
        boolean sw = Boolean.parseBoolean(ParamResolver.getStr(ConfigEnums.SYS_CAPTCHA_IMG.getValue(), "false"));
        if (sw) {
            // 验证码校验
            boolean captcha = sysCaptchaService.validate(req.getUuid(), req.getCaptchaCode());
            if (!captcha) {
                return Result.error("验证码不正确");
            }
        }
        User user = userService.getByUsername(req.getUsername());
        if (user == null) {
            return Result.error("该账户不存在");
        }
        if (user.getStatus().equals("0")){
            return Result.error("该账户被禁用，不能登录");
        }
        String result = userService.login(req);
        if (StringUtils.isEmpty(result)) {
            return Result.error("用户名或密码错误");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("result",result);
        map.put("expiredTime", JwtTokenUtil.getExpiredDateFromToken(result));
        return Result.success(map);
    }

    @LogAnnotation(module = "用户模块", operation = "用户注册")
    @PostMapping(value = "/register")
    public Result register(@RequestBody UserRegisterReq req) {
        return Result.success(userService.register(req));
    }

    @GetMapping("/captcha")
    public Result captcha() {
        CaptchaResult captchaResult = sysCaptchaService.getCaptcha();
        boolean sw = Boolean.parseBoolean(ParamResolver.getStr(ConfigEnums.SYS_CAPTCHA_IMG.getValue(), "false"));
        captchaResult.setEnabled(sw);
        return Result.success(captchaResult);
    }
    @LogAnnotation(module = "用户模块", operation = "导入用户")
    @PostMapping(value = "/import")
    public Result importUser(@RequestParam("file") MultipartFile file,@RequestParam("updateSupport")Integer updateSupport) {
        return Result.success(userService.importUser(file,updateSupport));
    }

    @LogAnnotation(module = "用户模块", operation = "导出用户")
    @GetMapping(value = "/export")
    public void exportUser(HttpServletResponse response) {
        userService.exportUser(response);
    }
}
